package com.jvtd.utils;

import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.IOException;

/**
 * Created by Administrator on 2017/10/16.
 * Shell工具类
 */
public class ShellUtils
{
  private ShellUtils()
  {
    throw new UnsupportedOperationException("u can't instantiate me...");
  }

  /**
   * 是否是在root下执行命令
   *
   * @param command 命令
   * @param isRoot  是否需要root权限执行
   * @return CommandResult
   */
  static CommandResult execCmd(final String command, final boolean isRoot)
  {
    return execCmd(new String[]{command}, isRoot);
  }

  /**
   * 是否是在root下执行命令
   *
   * @param commands        命令数组
   * @param isRoot          是否需要root权限执行
   * @return CommandResult
   */
  private static CommandResult execCmd(final String[] commands, final boolean isRoot)
  {
    int result = -1;
    if (commands == null || commands.length == 0)
    {
      return new CommandResult(result);
    }
    DataOutputStream os = null;
    Process process = null;
    try
    {
      process = Runtime.getRuntime().exec(isRoot ? "su" : "sh");
      os = new DataOutputStream(process.getOutputStream());
      for (String command : commands)
      {
        if (command == null) continue;
//        os.write(command.getBytes());
        os.writeBytes(command);
        os.writeBytes("\n");
        os.flush();
      }
      os.writeBytes("exit\n");
      os.flush();
      result = process.waitFor();
    } catch (Exception e)
    {
      e.printStackTrace();
    } finally
    {
      closeIO(os);
      if (process != null)
      {
        process.destroy();
      }
    }
    return new CommandResult(result);
  }

  private static void closeIO(final Closeable... closeables)
  {
    if (closeables == null) return;
    for (Closeable closeable : closeables)
    {
      if (closeable != null)
      {
        try
        {
          closeable.close();
        } catch (IOException e)
        {
          e.printStackTrace();
        }
      }
    }
  }

  /**
   * 返回的命令结果
   */
  static class CommandResult
  {
    /**
     * 结果码
     **/
    private int result;

    private CommandResult(final int result)
    {
      this.result = result;
    }

    public int getResult()
    {
      return result;
    }
  }
}
